var lockReconnect = false; //避免ws重复连接
var ws: any = null; // 判断当前浏览器是否支持WebSocket
// var wsUrl =
//     'wss://172.30.199.170:18883/integrate/ws/generationcenter/2eb2d3fe-4f10-4f23-9ba1-ad5069aed2d9/2';
// createWebSocket(wsUrl); //连接ws
let wsUrl: string = "";

function initEventHandle(handleMessage:(evt:MessageEvent) => {}) {
  ws.onclose = function() {
    reconnect(wsUrl,handleMessage);
    console.log("llws连接关闭!" + new Date().toLocaleString());
  };
  ws.onerror = function() {
    reconnect(wsUrl,handleMessage);
    console.log("llws连接错误!");
  };
  ws.onopen = function(e: any) {
    setTimeout(() => {
      if (e.currentTarget.readyState === 1) {
        console.log("llws连接成功!" + new Date().toLocaleString());
      }
    }, 1000);
    };
    console.log("initEventHandle");
    
  ws.onmessage = handleMessage;
}
// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function() {
  ws.close();
};

function reconnect(url: string, cb: (evt:MessageEvent) => {}) {
  if (lockReconnect) return;
  lockReconnect = true;
  setTimeout(function() {
    //没连接上会一直重连，设置延迟避免请求过多
    createWebSocket(url,cb);
    lockReconnect = false;
  }, 2000);
}

export function createWebSocket(url: string, cb: (evt:MessageEvent) => {}) {
  try {
    wsUrl = url;
    console.log("轮子", url);
    if ("WebSocket" in window) {
      ws = new WebSocket(url);
    }
    initEventHandle(cb);
  } catch (e) {
    reconnect(url,cb);
    console.log(e);
  }
}
